package com.css.fxfzypg.modules.maps.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.common.utils.AreaBoundaryUtil;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.modules.baseData.entity.AreaEntity;
import com.css.fxfzypg.modules.baseData.queryParams.AreaQueryParams;
import com.css.fxfzypg.modules.maps.entity.DistrictEntity;
import com.css.fxfzypg.modules.maps.queryParams.MapQueryParams;
import com.css.fxfzypg.modules.maps.service.TaskRegionMapService;
import com.css.fxfzypg.modules.qhmapfiles.repository.QhMapFilesImport;
import com.css.fxfzypg.modules.qhmapfiles.repository.QhMapFilesNativeRepository;
import com.css.fxfzypg.modules.qhmapfiles.repository.entity.QhMapFilesEntity;
import com.css.fxfzypg.modules.qhmapfiles.viewobjects.QhMapFilesQueryParams;
import com.css.fxfzypg.modules.spatialData.repository.BoundaryNativeRepository;
import com.css.fxfzypg.util.CreateGson;
import com.css.fxfzypg.util.PlatformDateUtils;
import com.css.fxfzypg.util.PlatformObjectUtils;
import com.css.fxfzypg.util.UUIDGenerator;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SUserService;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import com.css.fxfzypg.zcpt.sys.service.SysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.geometry.jts.JTS;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.filter.Filter;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author zyt
 * @Date: 2022/12/08
 */
@Service
@Slf4j
public class TaskRegionMapServiceImpl implements TaskRegionMapService {
    @Autowired
    private QhMapFilesImport qhMapFilesImport;//上传文件管理
    @Autowired
    private QhMapFilesNativeRepository qhMapFilesNativeRepository;
    @Resource
    JdbcTemplate jdbcTemplate;
    @Resource
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    SUserService sUserService;

    @Autowired
    SysAreaService sysAreaService;

    /**
     * 数据源
     * 10.19.41.111
     */
    @Value("${spring.datasource.url}")
    private String url = "";
    @Value("${spring.datasource.username}")
    private String name = "";
    @Value("${spring.datasource.password}")
    private String pwd = "";

    /**
     * 获取数据库连接
     * SQL语句
     */
    private Connection getConnection() throws Exception {
        //Class.forName("com.mysql.cj.jdbc.Driver");
        Class.forName("org.postgresql.Driver");
        Connection conn = DriverManager.getConnection(url, name, pwd);
        return conn;
    }

    //根据任务表类型、任务ID，查询行政区划--省|市|区县的名称和code列表
    @Override
    public List<List<String>> queryProvinceCityCountyNameCodeListByTaskId(String type,String taskId){
        //type:1现场调查任务2预评估任务
        //queryType:1省2市3区县
        List<List<String>> resultList = new ArrayList<List<String>>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            if (!PlatformObjectUtils.isEmpty(type) && !PlatformObjectUtils.isEmpty(taskId)) {
                conn = getConnection();
                List<String> nameList = new ArrayList<String>();//行政区划名称列表:省|市|区县|乡镇
                List<String> codeList = new ArrayList<String>();//行政区划编码列表:省|市|区县
                String tableName = "ypg_preassess_task";//预评估任务表
                if(type.equals("1")){
                    tableName = "ypg_survey_task";//现场调查任务表
                }else if(type.equals("2")){
                    tableName = "ypg_preassess_task";//预评估任务表
                }
                //查询行政区划
                String sql = "select c.name as province,c.code as code1,b.name as city,b.code as code2,a.name as county,a.code as code3 from district_boundary_county a " +
                        "left join district_boundary_city b on b.code=concat(subString(a.code,0,5),'00') " +
                        "left join district_boundary_province c on c.code=concat(subString(a.code,0,3),'0000')," +
                        "(select geom FROM "+tableName+" WHERE id = '"+taskId+"') t " +
                        "where ST_Intersects(a.geom,t.geom) " +
                        "and ST_Touches(a.geom,t.geom)!='t' " +
                        "order by a.code,b.code,c.code;";
                ps = conn.prepareStatement(sql);
                rs = ps.executeQuery();
                while (rs.next()) {
                    String province = rs.getString("province");//行政区划名称--省
                    String city = rs.getString("city");//行政区划名称--市
                    String county = rs.getString("county");//行政区划名称--区县
                    if (!PlatformObjectUtils.isEmpty(province) && !PlatformObjectUtils.isEmpty(city) && !PlatformObjectUtils.isEmpty(county)){
                        String name = province + "-" + city + "-" + county;
                        nameList.add(name);//行政区划名称--省-市-区县
                        String code1 = rs.getString("code1");//行政区划编码--省
                        String code2 = rs.getString("code2");//行政区划编码--市
                        String code3 = rs.getString("code3");//行政区划编码--区县
                        String code = code1 + "-" + code2 + "-" + code3;
                        codeList.add(code);
                    }
                }
                if(nameList.size()>0){
                    resultList.add(nameList);//行政区划名称列表
                    resultList.add(codeList);//行政区划编码列表
                }
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (ps != null) {
                    // 关闭连接
                    ps.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

        return resultList;
    }

    //根据任务表类型、任务ID，查询行政区划--省|市|区县|乡镇的名称和code列表
    @Override
    public List<List<String>> queryProvinceCityCountyStreetNameCodeListByTaskId(String type,String taskId){
        //type:1现场调查任务2预评估任务
        //queryType:1省2市3区县
        List<List<String>> resultList = new ArrayList<List<String>>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            if (!PlatformObjectUtils.isEmpty(type) && !PlatformObjectUtils.isEmpty(taskId)) {
                conn = getConnection();
                List<String> nameList = new ArrayList<String>();//行政区划名称列表:省|市|区县|乡镇
                List<String> codeList = new ArrayList<String>();//行政区划编码列表:省|市|区县
                String tableName = "ypg_preassess_task";//预评估任务表
                if(type.equals("1")){
                    tableName = "ypg_survey_task";//现场调查任务表
                }else if(type.equals("2")){
                    tableName = "ypg_preassess_task";//预评估任务表
                }
                //查询行政区划
                String sql = "select c.name as province,c.code as code1,b.name as city,b.code as code2,a.name as county,a.code as code3,d.street from district_boundary_county a " +
                        "left join district_boundary_city b on b.code=concat(subString(a.code,0,5),'00') " +
                        "left join district_boundary_province c on c.code=concat(subString(a.code,0,3),'0000') " +
                        "left join data_area d on d.province=c.name and d.city=b.name and d.county=a.name," +
                        "(select geom FROM "+tableName+" WHERE id = '"+taskId+"') t " +
                        "where ST_Intersects(a.geom,t.geom) " +
                        "and ST_Touches(a.geom,t.geom)!='t' " +
                        "order by a.code,b.code,c.code;";
                ps = conn.prepareStatement(sql);
                rs = ps.executeQuery();
                while (rs.next()) {
                    String province = rs.getString("province");//行政区划名称--省
                    String city = rs.getString("city");//行政区划名称--市
                    String county = rs.getString("county");//行政区划名称--区县
                    String street = rs.getString("street");//行政区划名称--乡镇、街道
                    if (!PlatformObjectUtils.isEmpty(province) && !PlatformObjectUtils.isEmpty(city) && !PlatformObjectUtils.isEmpty(county)){
                        String name = province + "-" + city + "-" + county;
                        if (!PlatformObjectUtils.isEmpty(street)){
                            name += "-" + street;
                            nameList.add(name);//行政区划名称--省-市-区县-乡镇、街道
                        }else{
                            nameList.add(name);//行政区划名称--省-市-区县
                        }
                        String code1 = rs.getString("code1");//行政区划编码--省
                        String code2 = rs.getString("code2");//行政区划编码--市
                        String code3 = rs.getString("code3");//行政区划编码--区县
                        String code = code1 + "-" + code2 + "-" + code3;
                        codeList.add(code);
                    }
                }
                if(nameList.size()>0){
                    resultList.add(nameList);//行政区划名称列表
                    resultList.add(codeList);//行政区划编码列表
                }
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (ps != null) {
                    // 关闭连接
                    ps.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

        return resultList;
    }

    //根据经纬度，查询行政区划--省|市|区县的名称和code列表
    @Override
    public List<List<String>> queryProvinceCityCountyNameCodeListByLonLat(String lon,String lat){
        List<List<String>> resultList = new ArrayList<List<String>>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            if (!PlatformObjectUtils.isEmpty(lon) && !PlatformObjectUtils.isEmpty(lat)) {
                String geomText = "POINT("+lon+" "+lat+")";
                conn = getConnection();
                List<String> nameList = new ArrayList<String>();//行政区划名称列表:省|市|区县|乡镇
                List<String> codeList = new ArrayList<String>();//行政区划编码列表:省|市|区县
                //查询行政区划
                String sql = "select c.name as province,c.code as code1,b.name as city,b.code as code2,a.name as county,a.code as code3 from district_boundary_county a " +
                        "left join district_boundary_city b on b.code=concat(subString(a.code,0,5),'00') " +
                        "left join district_boundary_province c on c.code=concat(subString(a.code,0,3),'0000') " +
                        "where ST_Intersects(a.geom,ST_GeometryFromText('"+geomText+"',4490)) " +
                        "order by a.code,b.code,c.code;";
                ps = conn.prepareStatement(sql);
                rs = ps.executeQuery();
                while (rs.next()) {
                    String province = rs.getString("province");//行政区划名称--省
                    String city = rs.getString("city");//行政区划名称--市
                    String county = rs.getString("county");//行政区划名称--区县
                    if (!PlatformObjectUtils.isEmpty(province) && !PlatformObjectUtils.isEmpty(city) && !PlatformObjectUtils.isEmpty(county)){
                        String name = province + "-" + city + "-" + county;
                        nameList.add(name);//行政区划名称--省-市-区县
                        String code1 = rs.getString("code1");//行政区划编码--省
                        String code2 = rs.getString("code2");//行政区划编码--市
                        String code3 = rs.getString("code3");//行政区划编码--区县
                        String code = code1 + "-" + code2 + "-" + code3;
                        codeList.add(code);
                    }
                }
                if(nameList.size()>0){
                    resultList.add(nameList);//行政区划名称列表
                    resultList.add(codeList);//行政区划编码列表
                }
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (ps != null) {
                    // 关闭连接
                    ps.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

        return resultList;
    }

    //根据地图圈选区域，查询行政区划--省|市|区县的名称和code列表
    @Override
    public List<List<String>> queryProvinceCityCountyNameCodeListByGeomText(String geomText){
        List<List<String>> resultList = new ArrayList<List<String>>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            if (!PlatformObjectUtils.isEmpty(geomText)) {
                conn = getConnection();
                List<String> nameList = new ArrayList<String>();//行政区划名称列表:省|市|区县|乡镇
                List<String> codeList = new ArrayList<String>();//行政区划编码列表:省|市|区县
                //查询行政区划
                String sql = "select c.name as province,c.code as code1,b.name as city,b.code as code2,a.name as county,a.code as code3 from district_boundary_county a " +
                        "left join district_boundary_city b on b.code=concat(subString(a.code,0,5),'00') " +
                        "left join district_boundary_province c on c.code=concat(subString(a.code,0,3),'0000')," +
                        "(select ST_GeometryFromText('"+geomText+"',4490) as geom) t " +
                        "where ST_Intersects(a.geom,t.geom) " +
                        "and ST_Touches(a.geom,t.geom)!='t' " +
                        "order by a.code,b.code,c.code;";
                ps = conn.prepareStatement(sql);
                rs = ps.executeQuery();
                while (rs.next()) {
                    String province = rs.getString("province");//行政区划名称--省
                    String city = rs.getString("city");//行政区划名称--市
                    String county = rs.getString("county");//行政区划名称--区县
                    if (!PlatformObjectUtils.isEmpty(province) && !PlatformObjectUtils.isEmpty(city) && !PlatformObjectUtils.isEmpty(county)){
                        String name = province + "-" + city + "-" + county;
                        nameList.add(name);//行政区划名称--省-市-区县
                        String code1 = rs.getString("code1");//行政区划编码--省
                        String code2 = rs.getString("code2");//行政区划编码--市
                        String code3 = rs.getString("code3");//行政区划编码--区县
                        String code = code1 + "-" + code2 + "-" + code3;
                        codeList.add(code);
                    }
                }
                if(nameList.size()>0){
                    resultList.add(nameList);//行政区划名称列表
                    resultList.add(codeList);//行政区划编码列表
                }
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (ps != null) {
                    // 关闭连接
                    ps.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

        return resultList;
    }

    //根据地图圈选区域，查询行政区划--省|市|区县|乡镇的名称和code列表
    @Override
    public List<List<String>> queryProvinceCityCountyStreetNameCodeListByGeomText(String geomText){
        List<List<String>> resultList = new ArrayList<List<String>>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            if (!PlatformObjectUtils.isEmpty(geomText)) {
                conn = getConnection();
                List<String> nameList = new ArrayList<String>();//行政区划名称列表:省|市|区县|乡镇
                List<String> codeList = new ArrayList<String>();//行政区划编码列表:省|市|区县
                //查询行政区划
                String sql = "select c.name as province,c.code as code1,b.name as city,b.code as code2,a.name as county,a.code as code3,d.street from district_boundary_county a " +
                        "left join district_boundary_city b on b.code=concat(subString(a.code,0,5),'00') " +
                        "left join district_boundary_province c on c.code=concat(subString(a.code,0,3),'0000') " +
                        "left join data_area d on d.province=c.name and d.city=b.name and d.county=a.name," +
                        "(select ST_GeometryFromText('"+geomText+"',4490) as geom) t " +
                        "where ST_Intersects(a.geom,t.geom) " +
                        "and ST_Touches(a.geom,t.geom)!='t' " +
                        "order by a.code,b.code,c.code;";
                ps = conn.prepareStatement(sql);
                rs = ps.executeQuery();
                while (rs.next()) {
                    String province = rs.getString("province");//行政区划名称--省
                    String city = rs.getString("city");//行政区划名称--市
                    String county = rs.getString("county");//行政区划名称--区县
                    String street = rs.getString("street");//行政区划名称--乡镇、街道
                    if (!PlatformObjectUtils.isEmpty(province) && !PlatformObjectUtils.isEmpty(city) && !PlatformObjectUtils.isEmpty(county)){
                        String name = province + "-" + city + "-" + county;
                        if (!PlatformObjectUtils.isEmpty(street)){
                            name += "-" + street;
                            nameList.add(name);//行政区划名称--省-市-区县-乡镇、街道
                        }else{
                            nameList.add(name);//行政区划名称--省-市-区县
                        }
                        String code1 = rs.getString("code1");//行政区划编码--省
                        String code2 = rs.getString("code2");//行政区划编码--市
                        String code3 = rs.getString("code3");//行政区划编码--区县
                        String code = code1 + "-" + code2 + "-" + code3;
                        codeList.add(code);
                    }
                }
                if(nameList.size()>0){
                    resultList.add(nameList);//行政区划名称列表
                    resultList.add(codeList);//行政区划编码列表
                }
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (ps != null) {
                    // 关闭连接
                    ps.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

        return resultList;
    }

    //zyt--根据预评估任务ID获取任务区域和地震影响场的并集的范围包括的省市区县名称
    @Override
    public List<DistrictEntity> getProvinceCityCountyListByTaskId(String taskId) {
        List<DistrictEntity> list = new ArrayList<DistrictEntity>();
        try{
            /*String sql="select c.name as province,c.code as provincecode,b.name as city,b.code as citycode," +
                    "a.name as county,a.code as countycode from district_boundary_county a " +
                    "left join district_boundary_city b on b.code=concat(subString(a.code,0,5),'00') " +
                    "left join district_boundary_province c on c.code=concat(subString(a.code,0,3),'0000') " +
                    "where ST_Intersects(a.geom,(select st_union(t.geom,(select m.geom from ypg_preassess_task m " +
                    "where id='"+taskId+"')) as geom from (" +
                    "select st_union(n.geom) as geom from setting_seismic_influenceflied n " +
                    "where n.task_id='"+taskId+"') t)) " +
                    "and ST_Touches(a.geom,(select st_union(t.geom,(select m.geom from ypg_preassess_task m " +
                    "where id='"+taskId+"')) as geom from (" +
                    "select st_union(n.geom) as geom from setting_seismic_influenceflied n " +
                    "where n.task_id='"+taskId+"') t))!='t' " +
                    "group by a.name,b.name,c.name,a.code,b.code,c.code " +
                    "order by a.code,b.code,c.code";*/
            String sql="select c.name as province,c.code as provincecode,b.name as city,b.code as citycode," +
                    "a.name as county,a.code as countycode from district_boundary_county a " +
                    "left join district_boundary_city b on b.code=concat(subString(a.code,0,5),'00') " +
                    "left join district_boundary_province c on c.code=concat(subString(a.code,0,3),'0000') " +
                    "where ST_Intersects(a.geom,(select geom from ypg_preassess_task where id='"+taskId+"')) " +
                    "or " +
                    "ST_Intersects(a.geom,(select st_union(n.geom) as geom from setting_seismic_influenceflied n where n.task_id='"+taskId+"')) " +
                    "group by a.name,b.name,c.name,a.code,b.code,c.code " +
                    "order by a.code,b.code,c.code";

            list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(DistrictEntity.class));

        }catch (Exception e){
            e.printStackTrace();
        }

        return list;
    }

    //根据任务ID、烈度、（区县|乡镇）统计人员死亡数
    public List<List<String>> countPbeInjuries(String taskId,String dzIntensity,String qcType){
        List<List<String>> resultList = new ArrayList<List<String>>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            if (!PlatformObjectUtils.isEmpty(taskId) && !PlatformObjectUtils.isEmpty(dzIntensity) && !PlatformObjectUtils.isEmpty(qcType)) {
                conn = getConnection();
                List<String> nameList = new ArrayList<String>();//行政区划名称列表:区县|乡镇
                List<String> sumList = new ArrayList<String>();//统计死亡人数
                if(qcType.equals("0")){//按区县统计
                    //查询行政区划
                    String sql = "select b.county,sum(a.death_num) from data_pbe_injuries a,data_pbe b " +
                            "where a.task_id='"+taskId+"' and a.dz_intentity='"+dzIntensity+"' " +
                            "and a.pbe_id=b.pbe_id GROUP BY b.county;";
                    ps = conn.prepareStatement(sql);
                    rs = ps.executeQuery();
                    while (rs.next()) {
                        String county = rs.getString("county");//行政区划名称--区县
                        String sum = rs.getString("sum");//统计死亡人数
                        if (!PlatformObjectUtils.isEmpty(county)){
                            nameList.add(county);
                            sumList.add(sum);
                        }
                    }
                    if(nameList.size()>0){
                        resultList.add(nameList);//行政区划名称列表
                        resultList.add(sumList);//统计死亡人数
                    }
                }else if(qcType.equals("1")) {//按乡镇统计
                    //查询行政区划
                    String sql = "select b.town,sum(a.death_num) from data_pbe_injuries a,data_pbe b " +
                            "where a.task_id='"+taskId+"' and a.dz_intentity='"+dzIntensity+"' " +
                            "and a.pbe_id=b.pbe_id GROUP BY b.town;";
                    ps = conn.prepareStatement(sql);
                    rs = ps.executeQuery();
                    while (rs.next()) {
                        String town = rs.getString("town");//行政区划名称--乡镇
                        String sum = rs.getString("sum");//统计死亡人数
                        if (!PlatformObjectUtils.isEmpty(town)){
                            nameList.add(town);
                            sumList.add(sum);
                        }
                    }
                    if(nameList.size()>0){
                        resultList.add(nameList);//行政区划名称列表
                        resultList.add(sumList);//统计死亡人数
                    }
                }
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (ps != null) {
                    // 关闭连接
                    ps.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

        return resultList;
    }

    //根据任务ID、烈度、（区县|乡镇）统计经济损失（万元）
    public List<List<String>> countPbeLosses(String taskId,String dzIntensity,String qcType){
        List<List<String>> resultList = new ArrayList<List<String>>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            if (!PlatformObjectUtils.isEmpty(taskId) && !PlatformObjectUtils.isEmpty(dzIntensity) && !PlatformObjectUtils.isEmpty(qcType)) {
                conn = getConnection();
                List<String> nameList = new ArrayList<String>();//行政区划名称列表:区县|乡镇
                List<String> sumList = new ArrayList<String>();//统计经济损失（万元）
                if(qcType.equals("0")){//按区县统计
                    //查询行政区划
                    String sql = "select b.county,sum(a.direct_losses) from data_pbe_losses a,data_pbe b " +
                            "where a.task_id='"+taskId+"' and a.dz_intentity='"+dzIntensity+"' " +
                            "and a.pbe_id=b.pbe_id GROUP BY b.county;";
                    ps = conn.prepareStatement(sql);
                    rs = ps.executeQuery();
                    while (rs.next()) {
                        String county = rs.getString("county");//行政区划名称--区县
                        String sum = rs.getString("sum");//统计经济损失（万元）
                        if (!PlatformObjectUtils.isEmpty(county)){
                            nameList.add(county);
                            sumList.add(sum);
                        }
                    }
                    if(nameList.size()>0){
                        resultList.add(nameList);//行政区划名称列表
                        resultList.add(sumList);//统计经济损失（万元）
                    }
                }else if(qcType.equals("1")) {//按乡镇统计
                    //查询行政区划
                    String sql = "select b.town,sum(a.direct_losses) from data_pbe_losses a,data_pbe b " +
                            "where a.task_id='"+taskId+"' and a.dz_intentity='"+dzIntensity+"' " +
                            "and a.pbe_id=b.pbe_id GROUP BY b.town;";
                    ps = conn.prepareStatement(sql);
                    rs = ps.executeQuery();
                    while (rs.next()) {
                        String town = rs.getString("town");//行政区划名称--乡镇
                        String sum = rs.getString("sum");//统计经济损失（万元）
                        if (!PlatformObjectUtils.isEmpty(town)){
                            nameList.add(town);
                            sumList.add(sum);
                        }
                    }
                    if(nameList.size()>0){
                        resultList.add(nameList);//行政区划名称列表
                        resultList.add(sumList);//统计经济损失（万元）
                    }
                }
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (ps != null) {
                    // 关闭连接
                    ps.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

        return resultList;
    }

    //根据任务ID、烈度、（区县|乡镇）统计需紧急安置人数
    public List<List<String>> countPbePlant(String taskId,String dzIntensity,String qcType){
        List<List<String>> resultList = new ArrayList<List<String>>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            if (!PlatformObjectUtils.isEmpty(taskId) && !PlatformObjectUtils.isEmpty(dzIntensity) && !PlatformObjectUtils.isEmpty(qcType)) {
                conn = getConnection();
                List<String> nameList = new ArrayList<String>();//行政区划名称列表:区县|乡镇
                List<String> sumList = new ArrayList<String>();//统计需紧急安置人数
                if(qcType.equals("0")){//按区县统计
                    //查询行政区划
                    String sql = "select b.county,sum(a.plant_person) from ypg_result_plant_pbe a,data_pbe b " +
                            "where a.task_id='"+taskId+"' and a.dz_intensity='"+dzIntensity+"' " +
                            "and a.pde_id=b.pbe_id GROUP BY b.county;";
                    ps = conn.prepareStatement(sql);
                    rs = ps.executeQuery();
                    while (rs.next()) {
                        String county = rs.getString("county");//行政区划名称--区县
                        String sum = rs.getString("sum");//统计需紧急安置人数
                        if (!PlatformObjectUtils.isEmpty(county)){
                            nameList.add(county);
                            sumList.add(sum);
                        }
                    }
                    if(nameList.size()>0){
                        resultList.add(nameList);//行政区划名称列表
                        resultList.add(sumList);//统计需紧急安置人数
                    }
                }else if(qcType.equals("1")) {//按乡镇统计
                    //查询行政区划
                    String sql = "select b.town,sum(a.plant_person) from ypg_result_plant_pbe a,data_pbe b " +
                            "where a.task_id='"+taskId+"' and a.dz_intensity='"+dzIntensity+"' " +
                            "and a.pde_id=b.pbe_id GROUP BY b.town;";
                    ps = conn.prepareStatement(sql);
                    rs = ps.executeQuery();
                    while (rs.next()) {
                        String town = rs.getString("town");//行政区划名称--乡镇
                        String sum = rs.getString("sum");//统计需紧急安置人数
                        if (!PlatformObjectUtils.isEmpty(town)){
                            nameList.add(town);
                            sumList.add(sum);
                        }
                    }
                    if(nameList.size()>0){
                        resultList.add(nameList);//行政区划名称列表
                        resultList.add(sumList);//统计需紧急安置人数
                    }
                }
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (ps != null) {
                    // 关闭连接
                    ps.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

        return resultList;
    }

    //校验shp文件
    public String checkSHPFiles(String filePath, String province, String city, String area, String formatDate, String userID) {
        try {
            String returnMsg = "";
            System.out.println(new Date()+"-------------------1.开始readSHPFile");
            System.out.println(new Date()+"-------------------2.开始校验");
            //校验是否为2000坐标系
            if (!(checkCGCS2000(filePath))){
                System.out.println(new Date()+"-----------校验失败.请上传正确的CGCS2000坐标系数据及.prj文件.");
                return "checkNotCGCS2000";
            }
            String cpgPath = filePath.substring(0, filePath.length() - 4) + ".cpg";
            String codeType = readCPG(cpgPath);//读取cpg文件编码
            //获取省市县所在区域字符串
            String boundariesCoordinate = getDistrictBoundaryCoordinate(province, city, area);
            //读取shp文件并校验--type上传类型（行政区划_）
            List<Object> list = readSHPFileCheck(filePath, codeType,"行政区划_", boundariesCoordinate);
            codeType = (String) list.get(0);//编码类型（0：UTF-8，1：GBK）
            int dataLength = (int) list.get(1);//数据长度
            String checkResult = (String) list.get(2);//校验结果
            //编码类型（0：UTF-8，1：GBK）
            if (codeType.equals("UTF-8")) {
                codeType = "0";
            }else{
                codeType = "1";
            }
            System.out.println(new Date()+"-------------------3.结束readSHPFile");
            System.out.println(new Date()+"-----------4.结束校验");
            if(checkResult.equals("校验成功")){
                System.out.println(new Date()+"-------------------1.完成校验GeometryIsNotEqualsCoordinate");
                System.out.println(new Date()+"-------------------2.完成校验是否有乱码");
                System.out.println(new Date()+"-------------------3.完成校验字段空值");
                //System.out.println(new Date()+"-------------------4.完成校验是否为罗马数字");
                System.out.println(new Date()+"-----------校验成功.");
                String fileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length() - 4);
                //上传文件信息
                QhMapFilesEntity qhMapFilesEntity = new QhMapFilesEntity();
                qhMapFilesEntity.setUuid(UUIDGenerator.getUUID());
                qhMapFilesEntity.setFilepath(filePath);
                qhMapFilesEntity.setProvince(province);
                qhMapFilesEntity.setCity(city);
                qhMapFilesEntity.setArea(area);
                qhMapFilesEntity.setAffiliatedFileName(fileName);
                qhMapFilesEntity.setDateStr(formatDate);
                qhMapFilesEntity.setIsSave("0");
                qhMapFilesEntity.setIsDelete("0");
                qhMapFilesEntity.setType("行政区划_");//类型
                qhMapFilesEntity.setPostfix("shp");
                qhMapFilesEntity.setQualityStatus("1");//上传省市级类型（0：省，1：市）
                qhMapFilesEntity.setCodeType(codeType);//编码类型（0：UTF-8，1：GBK）
                qhMapFilesEntity.setDataLength(dataLength);//数据长度
                qhMapFilesEntity.setCreateUser(userID);//登录人
                System.out.println(new Date()+"-------------------4.开始保存");
                //保存到上传文件管理表
                saveMapFiles(qhMapFilesEntity);
                //根据类型保存到数据库
                returnMsg = saveQhMapFilesToDatabaseByType(qhMapFilesEntity);
                System.out.println(new Date()+"-------------------5.结束保存");
            }else{
                System.out.println(new Date()+"-----------校验失败."+checkResult);
                returnMsg = "上传文件中第"+(dataLength+1)+"行数据#" + checkResult;
            }
            //返回的消息
            return returnMsg;
        } catch (RuntimeException e) {
            log.error(e.getMessage(), e);
            return "插入或更新数据出现错误: <br/>" + e.getMessage();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "数据导入失败, 服务器内部出现异常!";
        }
    }

    //根据类型保存到数据库
    public String saveQhMapFilesToDatabaseByType(QhMapFilesEntity qhMapFilesEntity) {
        String fileUuid = qhMapFilesEntity.getUuid();
        String type = qhMapFilesEntity.getType();
        String filePath = qhMapFilesEntity.getFilepath();
        String affiliatedFileName = qhMapFilesEntity.getAffiliatedFileName();
        String province = qhMapFilesEntity.getProvince();
        String city = qhMapFilesEntity.getCity();
        String area = qhMapFilesEntity.getArea();
        //String createUser  = qhMapFilesEntity.getCreateUser();
        String postfix = qhMapFilesEntity.getPostfix();//文件类型：shp | gdb
        String codeType = qhMapFilesEntity.getCodeType();//编码类型（0：UTF-8，1：GBK）
        int dataLength = qhMapFilesEntity.getDataLength();
        String createUser = qhMapFilesEntity.getCreateUser();//创建人
        String dateStr = qhMapFilesEntity.getDateStr();//日期
        if(codeType.equals("0")){
            codeType = "UTF-8";
        }else{
            codeType = "GBK";
        }
        System.out.println(new Date()+"------开始导入."+affiliatedFileName+"----数据长度."+dataLength);
        //test
        /*if(dataLength>1000000){
            return "导入失败."+affiliatedFileName+"数据长度过大"+dataLength;
        }*/
        String resMsg = affiliatedFileName;//返回结果
        String result = "";
        try{
            //更新为正在保存状态
            updateSaveNowQhMapFile(qhMapFilesEntity);
            //根据日期和类型查询全部文件
            QhMapFilesQueryParams queryParams = new QhMapFilesQueryParams();
            queryParams.setType(type);//上传类型（行政区划_）
            //queryParams.setIsDelete("0");//未删除
            //queryParams.setIsSave("0");//未保存
            //queryParams.setProvince(province);
            //queryParams.setCity(city);
            //queryParams.setArea(area);
            queryParams.setDateStr(dateStr);//日期
            List<QhMapFilesEntity> list = searchQhMapFilesByParams(queryParams);
            //上传日期的所有文件数量
            int fileListCount = 0;
            if(list!=null){
                fileListCount = list.size();
            }
            //保存
            if(postfix.equals("shp")){//保存shp文件
                result = newImportShapeFile(filePath,province,city,area,fileUuid,codeType,dataLength,createUser,dateStr,fileListCount);
            }else if(postfix.equals("gdb")){//保存GDB文件
                //result = this.qhProbabilityEarthquakeDangerService.newImportGDBFile(filePath,province,city,area,createUser,codeType,dataLength);
            }
            //已保存成功
            if(result.contains("成功导入")){
                /*if(list!=null && list.size()>0){
                    //批量更新为已删除状态
                    updateLogicDeleteQhMapFiles(list);
                }*/
                //更新为已保存状态
                updateSaveQhMapFile(qhMapFilesEntity);
                resMsg += "导入成功." + result + "当前数据所在文件UUID"+fileUuid;
            }else{
                resMsg += "导入失败." + result;
            }
        }catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return resMsg;
    }

    //保存shp文件数据
    public String newImportShapeFile(String filePath, String province, String city, String area, String fileUuid,String codeType,int dataLength, String createUser, String dateStr, int fileListCount) {
        // 返回的消息
        StringBuilder returnMsg = new StringBuilder();
        try {
            System.out.println(new Date()+"-------------------1.开始保存");
            //保存--zyt
            int count = newSaveData(filePath,province,city,area, codeType, dataLength,fileUuid,createUser,dateStr,fileListCount);
            if(count==dataLength){
                System.out.println(new Date()+"-------------------2.结束保存");
                returnMsg.append("成功导入" + count + "条数据.");
            }else{
                System.out.println(new Date()+"-------------------2.结束保存");
                returnMsg.append("导入出现异常，仅导入" + count + "条数据.");
            }
            return returnMsg.toString();
        } catch (RuntimeException e) {
            log.error(e.getMessage(), e);
            return "插入或更新数据出现错误: <br/>" + e.getMessage();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "数据导入失败, 服务器内部出现异常!";
        }
    }

    //保存shp文件数据
    private int newSaveData(String filePath, String province, String city, String area, String codeType, int dataLength, String fileUuid, String createUser, String dateStr, int fileListCount) {
        int count = 0;
        int num = 5000;//每次保存的数据长度
        Connection conn = null;
        try {
            conn = getConnection();
            String fileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length() - 4);
            String prjPath = filePath.substring(0, filePath.length() - 4) + ".prj";
            String strWKTMercator = readPRJ(prjPath);
            if (strWKTMercator != "") setStrWKTMercator(strWKTMercator);
            System.out.println(new Date()+"-------------------1.开始readSHPFile");
            SimpleFeatureCollection colls = readShp(filePath, null, codeType);
            System.out.println(new Date()+"-------------------2.结束readSHPFile");
            //String tableName = "district_boundary";
            //String tableName = "district_boundary_province";
            //String tableName = "district_boundary_city";
            String tableName = "district_boundary_county";
            //新增
            String tempsql = "insert into "+tableName+" (" +
                    "id,type,level,code,name," +
                    "geom) values ";
            if(tableName.equals("district_boundary")){
                tempsql = "insert into "+tableName+" (" +
                        "id,type,level,code,name," +
                        "coordinate) values ";
            }

            StringBuffer sql = new StringBuffer("");
            int total = dataLength;
            boolean bool = false;//是否保存
            //开始时间
            Long begin = new Date().getTime();
            String lonLatStr = "", wkt = "";
            SimpleFeatureIterator iters = colls.features();
            while (iters.hasNext()) {
                count++;
                bool = false;//是否保存
                if(count<total){
                    if(count % num == 0){
                        bool = true;//是否保存
                        //开始时间
                        begin = new Date().getTime();
                    }
                }else{
                    bool = true;//是否保存
                }
                SimpleFeature sf = iters.next();
                List<Object> values = sf.getAttributes();
                //空间数据
                String geo = values.get(0).toString();
                String geom = null;
                if (geo != null) {
                    geom = "ST_GeometryFromText('" + geo + "',4490)";
                }
                //主键
                String areaId = UUIDGenerator.getUUID();
                String type = "1";
                String level = "0";
                if(tableName.equals("district_boundary_province")){
                    level = "0";
                }else if(tableName.equals("district_boundary_city")){
                    level = "1";
                }else if(tableName.equals("district_boundary_county")){
                    level = "2";
                }
                String code = "71";//test台湾
                String name = values.get(3).toString();//test

                if(tableName.equals("district_boundary")){
                    sql.append("('" + areaId + "','" + type + "','" + level + "','" + code
                            + "','" + name
                            + "','" + geo +"'),");
                }else{
                    sql.append("('" + areaId + "','" + type + "','" + level + "','" + code
                            + "','" + name
                            + "'," + geom +"),");
                }

                if(bool){
                    String sql_str = tempsql + sql.toString();
                    sql_str = sql_str.substring(0, sql_str.length() - 1);
                    PreparedStatement ps = conn.prepareStatement(sql_str);
                    //ps.executeUpdate(sql_str);
                    ps.executeUpdate();
                    if (ps != null) ps.close();
                    //结束时间
                    Long end = new Date().getTime();
                    //耗时
                    System.out.println(new Date()+"----count: " + count+",cast : " + (end - begin) / 1000 + " s");
                    //清空
                    sql.setLength(0);
                }
            }
            iters.close();

        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("保存第" + count + "条数据出现异常!");
            //已保存的数量
            count = (int) Math.floor(count / num) * num;
        } finally {
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

        return count;
    }

    //更新为正在保存状态
    @Transactional(rollbackFor = Exception.class)
    public int updateSaveNowQhMapFile(QhMapFilesEntity qhMapFilesEntity) throws Exception {
        List<QhMapFilesEntity> list = new ArrayList<QhMapFilesEntity>();
        list.add(qhMapFilesEntity);
        int count = qhMapFilesImport.sqlBatchUpdateNowEntities(list);

        return count;
    }

    //批量更新为已删除状态
    @Transactional(rollbackFor = Exception.class)
    public int updateLogicDeleteQhMapFiles(List<QhMapFilesEntity> list) throws Exception {
        int count = qhMapFilesImport.sqlBatchLogicDeleteEntities(list);

        return count;
    }

    //更新为已保存状态
    @Transactional(rollbackFor = Exception.class)
    public int updateSaveQhMapFile(QhMapFilesEntity qhMapFilesEntity) throws Exception {
        List<QhMapFilesEntity> list = new ArrayList<QhMapFilesEntity>();
        list.add(qhMapFilesEntity);
        int count = qhMapFilesImport.sqlBatchUpdateEntities(list);

        return count;
    }

    //根据参数查询文件
    public List<QhMapFilesEntity> searchQhMapFilesByParams(QhMapFilesQueryParams queryParams) {
        List<QhMapFilesEntity> list = qhMapFilesNativeRepository.searchMapFilesByJDBC(queryParams);

        return list;
    }

    //校验是否为2000坐标系
    public boolean checkCGCS2000(String path) {
        String prjPath = path.substring(0, path.length() - 4) + ".prj";
        String strWKTMercator = readPRJ(prjPath);
        if (strWKTMercator == "") return false;
        CoordinateReferenceSystem sourceTarget = null;
        try {
            sourceTarget = CRS.parseWKT(strWKTMercator);
        } catch (FactoryException e) {
            e.printStackTrace();
            System.out.println(path + ": 解析错误!");
        }
        String name = sourceTarget.getName().toString();
        if (name.equals("GCS_China_Geodetic_Coordinate_System_2000")) return true;

        return false;
    }

    //保存到上传文件管理表
    private void saveMapFiles(QhMapFilesEntity qhMapFilesEntity) throws Exception {
        List<QhMapFilesEntity> list = new ArrayList<QhMapFilesEntity>();
        list.add(qhMapFilesEntity);
        String affiliatedFileName = qhMapFilesEntity.getAffiliatedFileName();
        String province = qhMapFilesEntity.getProvince();
        String city = qhMapFilesEntity.getCity();
        String area = qhMapFilesEntity.getArea();
        //逻辑删除未保存的文件
        deleteMapFileByParams(affiliatedFileName, province, city, area);
        //保存
        qhMapFilesImport.sqlBatchSaveEntities(list);
    }

    //逻辑删除未保存的文件
    private void deleteMapFileByParams(String affiliatedFileName, String province, String city, String area) {
        //查询上传文件表
        QhMapFilesQueryParams qhMapFilesQueryParams = new QhMapFilesQueryParams();
        qhMapFilesQueryParams.setProvince(province);
        qhMapFilesQueryParams.setCity(city);
        qhMapFilesQueryParams.setArea(area);
        //qhMapFilesQueryParams.setAffiliatedFileName(affiliatedFileName);
        qhMapFilesQueryParams.setType("行政区划_");//上传类型（行政区划_）
        //查询文件（未删除）
        List<QhMapFilesEntity> list = qhMapFilesImport.searchMapFilesUnSaved(qhMapFilesQueryParams);
        if(!PlatformObjectUtils.isEmpty(list) && list.size() > 0) {
            //逻辑删--上传文件表
            qhMapFilesImport.sqlBatchLogicDeleteEntities(list);
        }
    }

    @Autowired
    private BoundaryNativeRepository boundaryNativeRepository;
    //获取省市县所在区域字符串
    public String getDistrictBoundaryCoordinate(String province, String city, String area){
        String coordinate = "";
        return coordinate;
        /*BoundaryQueryParams queryParams = new BoundaryQueryParams();
        queryParams.setType("1");//1: 行政区划 2: 普查区划
        if(PlatformObjectUtils.isEmpty(area)){//市
            queryParams.setLevel("1");//0: 省 1: 市 2: 县
            queryParams.setName(city);
        }else{//县
            queryParams.setLevel("2");//0: 省 1: 市 2: 县
            queryParams.setName(area);
        }
        queryParams.setProvince(province);
        queryParams.setCity(city);
        queryParams.setArea(area);
        //查询省市县所在区域边界列表
        List<BoundaryEntity> boundaryEntities = this.boundaryNativeRepository.newListBoundaries(queryParams);
        if (boundaryEntities.size() == 1) {
            BoundaryEntity boundaryEntity = boundaryEntities.get(0);
            coordinate = boundaryEntity.getCoordinate();

        } else if (boundaryEntities.size() == 0) {
            System.out.println("NoDistrictBoundaryData");
        } else {
            System.out.println("DistrictBoundaryDataRedundance");
        }
        return coordinate;*/
    }

    //读取shp文件并校验--type上传类型（行政区划_）
    public List<Object> readSHPFileCheck(String path, String codeType,String type, String boundariesCoordinate) {
        List<Object> result = new ArrayList<Object>();
        String prjPath = path.substring(0, path.length() - 4) + ".prj";
        String strWKTMercator = readPRJ(prjPath);
        if (strWKTMercator != "") setStrWKTMercator(strWKTMercator);
        String lonLatStr = "", wkt = "";
        SimpleFeatureCollection colls1 = readShp(path, null, codeType);
        SimpleFeatureIterator iters = colls1.features();
        String resMsg = "校验成功";
        int count = 0;
        //校验空间分辨率不是6秒
        double lon = 0, lat = 0;
        //List<String> allWktStrList = new ArrayList<String>();//全部空间信息字符串列表
        List<Double> allLonList = new ArrayList<Double>();
        List<Double> allLatList = new ArrayList<Double>();
        SimpleFeature sf = null;

        //校验矢量面是否在省市县所在区域内
        List<List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon>> multiPolygonList = new ArrayList<List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon>>();
        List<Geometry> multiPolygonGeometryList = new ArrayList<Geometry>();
        //Geometry boundariesGeometry = null;//行政区域
        //boundariesGeometry = getPolygonGeometryList(boundariesCoordinate);//行政区域
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Point[]> boundaries = getDistrictBoundaryByString(boundariesCoordinate);

        while (iters.hasNext()) {
            if(count%100000==0){
                System.out.println(count);
            }
            sf = iters.next();
            List<Object> attributes = sf.getAttributes();
            //0.判断字段数量是否符合要求
            int size = attributes.size();
            if("行政区划_".equals(type)){
                if(size<5){
                    resMsg = "fieldNumError";
                    break;
                }
            }
            //校验矢量面是否在省市县所在区域内
            /*if("RLMPolygon_".equals(type)){
                //根据属性获取矢量面列表
                List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon> polygonList = getPolygonList(attributes);
                //校验数据是否在省市县所在区域边界内
                if(!newCheckPointIsInDistrict(boundaries, polygonList)){
                    resMsg = "PointIsNotInDistrict";
                    break;
                }

                //添加到面经纬度列表用于校验面是否相交
                multiPolygonList.add(polygonList);
                //test
                Geometry polygon = getPolygonGeometryList(attributes.get(0).toString());
                multiPolygonGeometryList.add(polygon);
            }*/
            if("行政区划_".equals(type)){
                //1.校验GeometryIsNotEqualsCoordinate
                String pointWkt = attributes.get(0).toString();
                /*String A = attributes.get(1).toString();//经度
                String B = attributes.get(2).toString();//纬度
                //新校验经纬度方法
                if (!newGeometryIsEqualsCoordinate(pointWkt, A, B)) {
                    resMsg = "GeometryIsNotEqualsCoordinate";
                    break;
                }*/

                /*//可注释判断以下判断点是否在行政区划内代码
                //判断点是否在行政区划内
                if(!newCheckPointIsInDistrictBoundary(boundaries,A,B)){
                    resMsg = "PointIsNotInDistrict";
                    break;
                }*/
            }
            //2.校验是否有乱码
            int msssyIndex = -1;
            //校验是否有乱码
            for (int j = 0; j < attributes.size(); j++) {
                if(attributes.get(j)==null){
                    continue;
                }
                String value = attributes.get(j).toString();
                for (int k = 0; k < value.length() / 2; k++) {
                    char c = value.charAt(k);
                    // 当从Unicode编码向某个字符集转换时，如果在该字符集中没有对应的编码，则得到0x3f（即问号字符?）
                    //从其他字符集向Unicode编码转换时，如果这个二进制数在该字符集中没有标识任何的字符，则得到的结果是0xfffd
                    if ((int) c == 0xfffd) {
                        // 存在乱码
                        msssyIndex = count;
                        break;
                    }
                }
                if(msssyIndex!=-1){
                    resMsg = "messyCode";
                    break;
                }
            }
            if(msssyIndex!=-1){
                break;
            }
            //3.校验字段空值
            for (int j = 0; j < attributes.size(); j++) {
                //非必填
                if(j>1){
                    break;
                }
                if(attributes.get(j)==null){
                    resMsg = "fieldNullValue";
                    break;
                }
                String value = attributes.get(j).toString();
                //校验字段空值
                if (value == null || "".equals(value.trim())){
                    resMsg = "fieldNullValue";
                    break;
                }
            }
            if(!resMsg.equals("校验成功")){
                break;
            }
            //上传类型（行政区划_）
            /*if ("行政区划_".equals(type)) {
                //4.校验空间分辨率不是6秒
                String A = attributes.get(1).toString();
                String B = attributes.get(2).toString();
                lon = Double.parseDouble(A);
                lat = Double.parseDouble(B);
                allLonList.add(lon);
                allLatList.add(lat);
                //校验是否空间位置重叠
                //allWktStrList.add(attributes.get(0).toString());
            }*/

            //4.校验数据内容是否符合规范
            if ("行政区划_".equals(type)) {
                //
            }

            count++;
        }
        iters.close();
        System.out.println(count);

        //返回结果
        result.add(codeType);//编码类型（0：UTF-8，1：GBK）
        result.add(count);//数据长度
        result.add(resMsg);//校验结果
        //校验是否有乱码
        if(resMsg.indexOf("messyCode")!=-1 && !codeType.equals("GBK")){
            result = readSHPFileCheck(path, "GBK",type, boundariesCoordinate);
        }

        return result;
    }

    //读取cpg文件编码
    public String readCPG(String path) {
        String codeType = "UTF-8";
        StringBuffer result = new StringBuffer();
        File file = new File(path);
        if (!file.exists()) return "";
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                result.append(tempString);
            }
            reader.close();
            //返回结果
            codeType = result.toString();
            codeType = codeType.toUpperCase();//转换大写
        } catch (IOException e) {
            e.printStackTrace();
        }
        return codeType;
    }

    public String readPRJ(String path) {
        StringBuffer result = new StringBuffer();
        File file = new File(path);
        if (!file.exists()) return "";
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                result.append(tempString);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    public SimpleFeatureCollection readShp(String path, Filter filter, String codeType) {
        SimpleFeatureSource featureSource = readStoreByShp(path, codeType);
        if (featureSource == null) return null;
        try {
            return filter != null ? featureSource.getFeatures(filter) : featureSource.getFeatures();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public SimpleFeatureSource readStoreByShp(String path, String codeType) {
        File file = new File(path);
        FileDataStore store;
        SimpleFeatureSource featureSource = null;
        try {
            store = FileDataStoreFinder.getDataStore(file);
            ((ShapefileDataStore) store).setCharset(Charset.forName(codeType));
            featureSource = store.getFeatureSource();
            store.dispose();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return featureSource;
    }

    //获取省市县所在区域边界列表
    public List<com.css.fxfzypg.modules.spatialData.repository.entity.Point[]> getDistrictBoundaryByString(String coordinate){
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Point[]> boundaries = new ArrayList<>();
        if (coordinate == null || "".equals(coordinate)) {
            System.out.println("NoDistrictBoundaryData");
        } else {
            coordinate = coordinate.substring(coordinate.indexOf("(((") + 3, coordinate.lastIndexOf(")))"));
            coordinate = coordinate.replace(")), ((", "|");
            //coordinate = coordinate.replace("), (", "#");
            coordinate = coordinate.replace("), (", "|");
            String[] coordinates = StringUtils.split(coordinate, "|");
            for (int j = 0; j < coordinates.length; j++) {
                coordinates[j] = coordinates[j].replace(", ",";");
                coordinates[j] = coordinates[j].replace(" ",",");
                String[] lonlats = StringUtils.split(coordinates[j],";");
                com.css.fxfzypg.modules.spatialData.repository.entity.Point[] points = new com.css.fxfzypg.modules.spatialData.repository.entity.Point[lonlats.length];
                for (int i = 0;i < lonlats.length;i++) {
                    String[] lonlat = StringUtils.split(lonlats[i], ",");
                    com.css.fxfzypg.modules.spatialData.repository.entity.Point point = new com.css.fxfzypg.modules.spatialData.repository.entity.Point();
                    point.x = Double.parseDouble(lonlat[0]);
                    point.y = Double.parseDouble(lonlat[1]);
                    points[i] = point;
                }
                boundaries.add(points);
            }
        }

        return boundaries;
    }

    public String reverseWktMultiPolygon(String wktPolygon) {
        String oldWkt = wktPolygon;
        oldWkt = oldWkt.substring(oldWkt.indexOf("(((") + 3, oldWkt.lastIndexOf(")))"));
        oldWkt = oldWkt.replace(")), ((", "|");
        oldWkt = oldWkt.replace("), (", "#");

        String wktPolygon1 = "";
        String[] polygon1 = StringUtils.split (oldWkt, "|");
        for (int i = 0; i < polygon1.length; i++) {
            if(polygon1[i].indexOf("#")!=-1){
                String[] polygon2 = StringUtils.split(polygon1[i], "#");
                for (int j = 0; j < polygon2.length; j++) {
                    String wktPolygon2 = "";
                    String[] coords = polygon2[j].split(", ");
                    for (int k = 0; k < coords.length; k++) {
                        String[] lonLat = coords[k].split(" ");
                        String lon = lonLat[1];
                        String lat = lonLat[0];
                        wktPolygon2 += lon + " " + lat + ", ";
                    }
                    wktPolygon1 += wktPolygon2.substring(0, wktPolygon2.length() - 2) + "), (";
                }
                wktPolygon1 = wktPolygon1.substring(0, wktPolygon1.length() - 4) + ")), ((";
            }else{
                String wktPolygon2 = "";
                String[] coords = polygon1[i].split(", ");
                for (int k = 0; k < coords.length; k++) {
                    String[] lonLat = coords[k].split(" ");
                    String lon = lonLat[1];
                    String lat = lonLat[0];
                    wktPolygon2 += lon + " " + lat + ", ";
                }
                wktPolygon1 += wktPolygon2.substring(0, wktPolygon2.length() - 2) + ")), ((";
            }
        }
        wktPolygon1 = wktPolygon1.substring(0, wktPolygon1.length() - 6);

        return "MULTIPOLYGON (((" + wktPolygon1 + ")))";
    }

    public String reverseWktPolygon(String wktPolygon) {
        String oldWkt = wktPolygon;
        oldWkt = oldWkt.substring(oldWkt.indexOf("(") + 2, oldWkt.lastIndexOf("))"));

        String polygonWkt = "Polygon (", coordinate = "";
        String sp = oldWkt.indexOf("),(") != -1 ? "),(" : (oldWkt.indexOf("), (") != -1 ? "), (" : "");
        if ("".equals(sp)) {
            coordinate = "(";
            String[] coordinates = oldWkt.split(",");
            for (int i = 0; i < coordinates.length; i++) {
                String[] coords = coordinates[i].split(" ");
                coordinate += coords[1] + " " + coords[0] + ",";
            }
            coordinate = coordinate.substring(0, coordinate.length() - 1) + ")";
            polygonWkt += coordinate + ")";
        } else {
            oldWkt = oldWkt.replace(sp, "#"); sp = "#";
            String[] coordinates = oldWkt.split(sp);
            for (int i = 0; i < coordinates.length; i++) {
                coordinate = coordinates[i];
                String _coordinates = "(";
                String[] coords = coordinate.split(","), _coords = null;
                for (int j = 0; j < coords.length; j++) {
                    _coords = coords[j].split(" ");
                    _coordinates += _coords[1] + " " + _coords[0] + ",";
                }
                _coordinates = _coordinates.substring(0, _coordinates.length() - 1) + ")";
                polygonWkt += _coordinates + ",";
            }
            polygonWkt += polygonWkt.substring(0, polygonWkt.length() - 1) + ")";
        }
        return polygonWkt;
    }

    public String reverseWktPoint(String wktPoint) {
        String oldWkt = wktPoint;
        oldWkt = oldWkt.substring(oldWkt.indexOf("(") + 1, oldWkt.lastIndexOf(")"));
        String[] coords = oldWkt.split(" ");
        return "POINT (" + coords[1] + " " + coords[0] + ")";
    }

    public String reverseWktMultiPoint(String wktMultiPoint) {
        String oldWkt = wktMultiPoint;
        oldWkt = oldWkt.substring(oldWkt.indexOf("(") + 2, oldWkt.lastIndexOf(")") - 1);
        String sp = oldWkt.indexOf("),(") != -1 ? "),(" : (oldWkt.indexOf("), (") != -1 ? "), (" : "");
        String[] coordinates = StringUtils.split(oldWkt, sp);
        String newWkt = "MULTIPOINT ((", coordinate = "";
        String[] coords = null;
        for (int i = 0; i < coordinates.length; i++) {
            coordinate = coordinates[i];
            coords = coordinate.split(" ");
            //newWkt += "(" + coords[1] + " " + coords[0] + "),";
            newWkt += coords[1] + " " + coords[0] + ",";
        }
        newWkt = newWkt.substring(0, newWkt.length() - 1) + "))";
        return newWkt;
    }

    //根据属性获取boundary.Point数组列表
    public List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon> getPolygonList(List<Object> attributes) {
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Point> pointArray0 = null;//面点数组
        List<List<com.css.fxfzypg.modules.spatialData.repository.entity.Point>> noPointList = null;//镂空的面点数组列表
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Point> pointArray = null;
        com.css.fxfzypg.modules.spatialData.repository.entity.Point point = null;
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon> polygonList = new ArrayList<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon>();
        com.css.fxfzypg.modules.spatialData.repository.entity.Polygon polygon = null;

        String coordinates = attributes.get(0).toString();
        try{
            if (coordinates.indexOf("MULTIPOLYGON") != -1) {
                coordinates = coordinates.substring(coordinates.indexOf("(((") + 3, coordinates.lastIndexOf(")))"));
                if (coordinates.indexOf(")), ((") != -1) {//多个面
                    coordinates = coordinates.replace(")), ((", "|");
                    coordinates = coordinates.replace("), (", "#");
                    String[] geometries = StringUtils.split(coordinates, "|");
                    for (int j = 0; j < geometries.length; j++) {
                        String geometry = geometries[j];
                        //获取面
                        polygon = new com.css.fxfzypg.modules.spatialData.repository.entity.Polygon(geometry);
                        polygonList.add(polygon);
                    }

                }else if (coordinates.indexOf("), (") != -1) {//单个面（包括镂空的面）
                    coordinates = coordinates.replace("), (", "#");
                    //获取面
                    polygon = new com.css.fxfzypg.modules.spatialData.repository.entity.Polygon(coordinates);
                    polygonList.add(polygon);

                }else{//单个面
                    //获取面
                    polygon = new com.css.fxfzypg.modules.spatialData.repository.entity.Polygon(coordinates);
                    polygonList.add(polygon);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            //System.out.println("矢量面："+attributes.get(0).toString());
        }

        return polygonList;
    }

    //根据属性获取矢量面Geometry
    public Geometry getPolygonGeometryList(String coordinates) {
        Geometry geometry = null;
        try{
            GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
            WKTReader reader = new WKTReader(geometryFactory);
            geometry = reader.read(coordinates);
        }catch (Exception e){
            e.printStackTrace();
        }

        return geometry;
    }

    public boolean newGeometryIsEqualsCoordinate(String wkt, String lon, String lat) {
        String wktPart = "";
        if (wkt.toLowerCase().indexOf("multipoint") != -1) {
            wktPart = wkt.substring(wkt.indexOf("(") + 2, wkt.lastIndexOf(")") - 1);
        } else if (wkt.toLowerCase().indexOf("point") != -1) {
            wktPart = wkt.substring(wkt.indexOf("(") + 1, wkt.lastIndexOf(")"));
        }

        int det = 1 + 8;//保留8位小数判断
        String[] array = wktPart.split(" ");
        String longitude = array[0], latitude = array[1];
        String newWktLongitudeStr = newKeepDecimalDigits(longitude, det), newWktLatitudeStr = newKeepDecimalDigits(latitude, det);
        String newLongitudeStr = newKeepDecimalDigits(lon, det), newLatitudeStr = newKeepDecimalDigits(lat, det);

        double newWktLongitude = Double.parseDouble(newWktLongitudeStr), newWktLatitude = Double.parseDouble(newWktLatitudeStr);
        double newLongitude = Double.parseDouble(newLongitudeStr), newLatitude = Double.parseDouble(newLatitudeStr);

        //if (newWktLongitude == newLongitude && newWktLatitude == newLatitude) return true;
        //判断是否在10-6次方内
        double tempLon = Math.abs(newWktLongitude - newLongitude);
        double tempLat = Math.abs(newWktLatitude - newLatitude);
        if(tempLon<0.000001 && tempLat<0.000001){
            return true;
        }

        //判断保留8位（不四舍五入）属性字段经纬度与geometry是否一致
        if(getGeometryIsEqualsCoordinateBool(longitude, latitude, lon, lat, det)) return true;

        return false;
    }

    private String newKeepDecimalDigits(String floatStr, int det) {
        int index = floatStr.indexOf("."), len = floatStr.length();
        if (index == -1) return floatStr;
        int temp=det+1;
        String tempfloatPart=floatStr.substring(index + 1, (len > (index + temp)) ? (index + temp) : len);
        String floatPart = floatStr.substring(index + 1, (len > (index + det)) ? (index + det) : len);

        boolean bool = false;//判断是否四舍五入
        int findex=0;
        String sindex="";
        if(tempfloatPart.length()>floatPart.length()){
            if(tempfloatPart.startsWith(floatPart)&&(tempfloatPart.endsWith("9") || tempfloatPart.endsWith("8") || tempfloatPart.endsWith("7") || tempfloatPart.endsWith("6") || tempfloatPart.endsWith("5"))){
                for(int i=floatPart.length()-1;i>=0;i--){
                    String subStr = floatPart.substring(i, i+1);
                    if(subStr.equals("9")){
                        continue;
                    }
                    findex=i;
                    sindex=Integer.toString(Integer.parseInt(subStr)+1);
                    break;
                }
                floatPart= floatPart.substring(0, findex)+ sindex;
                bool = true;
            }
        }

        String newFloatStr = floatStr.substring(0, index) + "." + floatPart;
        if(bool && sindex.equals("")){//floatPart都是9
            newFloatStr = Integer.toString(Integer.parseInt(floatStr.substring(0, index))+1);
        }

        return newFloatStr;
    }

    //保留8位（不四舍五入）
    private String newKeepDecimalDigits2(String floatStr, int det) {
        int index = floatStr.indexOf("."), len = floatStr.length();
        if (index == -1) return floatStr;
        String floatPart = floatStr.substring(index + 1, (len > (index + det)) ? (index + det) : len);
        String newFloatStr = floatStr.substring(0, index) + "." + floatPart;

        return newFloatStr;
    }

    //判断保留8位（不四舍五入）属性字段经纬度与geometry是否一致
    private boolean getGeometryIsEqualsCoordinateBool(String longitude, String latitude, String lon, String lat, int det){
        boolean bool = false;
        String newWktLongitudeStr = newKeepDecimalDigits2(longitude, det), newWktLatitudeStr = newKeepDecimalDigits2(latitude, det);
        String newLongitudeStr = newKeepDecimalDigits2(lon, det), newLatitudeStr = newKeepDecimalDigits2(lat, det);

        double newWktLongitude = Double.parseDouble(newWktLongitudeStr), newWktLatitude = Double.parseDouble(newWktLatitudeStr);
        double newLongitude = Double.parseDouble(newLongitudeStr), newLatitude = Double.parseDouble(newLatitudeStr);

        //if (newWktLongitude == newLongitude && newWktLatitude == newLatitude) bool= true;
        //判断是否在10-6次方内
        double tempLon = Math.abs(newWktLongitude - newLongitude);
        double tempLat = Math.abs(newWktLatitude - newLatitude);
        if(tempLon<0.000001 && tempLat<0.000001){
            bool= true;
        }

        return bool;
    }

    //截取8位小数（不四舍五入）
    public String getNewDecimalDigits(String floatStr) {
        int det = 1 + 8;
        int index = floatStr.indexOf("."), len = floatStr.length();
        if (index == -1) return floatStr;
        String floatPart = floatStr.substring(index + 1, (len > (index + det)) ? (index + det) : len);
        String newFloatStr = floatStr.substring(0, index) + "." + floatPart;

        return newFloatStr;
    }

    //地球半径,单位 km
    private double EARTH_RADIUS = 6378.137;

    //根据经纬度，计算两点间的距离
    public double getDistance(double longitude1, double latitude1, double longitude2, double latitude2) {
        // 纬度
        double lat1 = Math.toRadians(latitude1);
        double lat2 = Math.toRadians(latitude2);
        // 经度
        double lng1 = Math.toRadians(longitude1);
        double lng2 = Math.toRadians(longitude2);
        // 纬度之差
        double a = lat1 - lat2;
        // 经度之差
        double b = lng1 - lng2;
        // 计算两点距离的公式
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
                Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(b / 2), 2)));
        // 弧长乘地球半径, 返回单位: 千米
        s =  s * EARTH_RADIUS;
        return s;
    }

    //判断6秒距离200
    public boolean isLessSixSecondDistance(List<Double> allLonList,List<Double> allLatList) {
        for(int i=0;i<allLonList.size();i++){
            if(i>100){//只判断100个点
                break;
            }
            double lng1 = allLonList.get(i);
            double lat1 = allLatList.get(i);
            boolean bool = false;
            double minDistance = -1;//最小距离
            for(int j=0;j<allLonList.size();j++){
                if(j==i){
                    continue;
                }
                double lng2 = allLonList.get(j);
                double lat2 = allLatList.get(j);
                double distance = getDistance(lng1,lat1,lng2,lat2);
                if(minDistance==-1 || distance<minDistance){
                    minDistance = distance;
                }
                if(distance<0.25){//250米
                    bool = true;
                    break;
                }
            }
            if(bool==false){
                System.out.println("第"+i+"条数据判断6秒距离不在250米内："+minDistance+"km--minDistance");
                System.out.println("第"+i+"条数据经纬度："+lng1+","+lat1);
                return false;
            }
        }

        return true;
    }

    //校验矢量面是否在存在单要素自相交
    public String checkIsPolygonsIntersect(List<List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon>> multiPolygonList) {
        String resultStr = "校验成功";
        com.css.fxfzypg.modules.spatialData.repository.entity.Polygon polygon = null;
        com.css.fxfzypg.modules.spatialData.repository.entity.Polygon polygon1 = null;
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon> polygonList = null;
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon> allPolygonList = null;//全部面列表
        if(multiPolygonList!=null && multiPolygonList.size()>0) {
            allPolygonList = new ArrayList<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon>();
            for (int n = 0; n < multiPolygonList.size(); n++) {
                polygonList = multiPolygonList.get(n);
                for (int i = 0; i < polygonList.size(); i++) {
                    allPolygonList.add(polygonList.get(i));
                }
            }
        }
        if(allPolygonList!=null && allPolygonList.size()>0) {
            for (int i = 0; i < allPolygonList.size(); i++) {
                polygon = allPolygonList.get(i);
                //判断矢量面是否存在自相交
                if(checkIsPolygonSelfIntersect(polygon)){
                    resultStr = "isPolygonSelfIntersect";
                    String temp = "面自相交";
                    System.out.println(temp);
                    break;
                }
            }
        }

        return resultStr;
    }

    //判断矢量面是否存在自相交
    private boolean checkIsPolygonSelfIntersect(com.css.fxfzypg.modules.spatialData.repository.entity.Polygon polygon){
        boolean bool = false;//不存在自相交
        int flag = 0;
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Point> points = polygon.points;
        for(int i = 0;i < (points.size()-1);i++){ //循环开始元素
            for(int j = i + 1;j < points.size();j++){ //循环后续所有元素
                //如果相等，则重复
                if(points.get(i).x == points.get(j).x && points.get(i).y == points.get(j).y){
                    flag++; //设置标志变量为重复
                }
            }
        }
        if(flag>1){//除首尾点外存在重复的点
            bool = true;//存在自相交
        }

        return bool;
    }

    private double GLOBAL_THRESH = 1E-6;
    //校验矢量面是否在存在两两重叠或相交（或单要素自相交）
    public String checkIsPolygonGeometrysIntersect(List<Geometry> multiPolygonGeometryList) {
        String resultStr = "校验成功";
        Geometry geometry1 = null;
        Geometry geometry2 = null;
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon> polygonList = null;
        if(multiPolygonGeometryList!=null && multiPolygonGeometryList.size()>0) {
            for (int i = 0; i < multiPolygonGeometryList.size(); i++) {
                geometry1 = multiPolygonGeometryList.get(i);
                //Geometry geometry1IntersectGeometry1 = geometry1.intersection(geometry1);
                //判断是否存在两两重叠或相交
                for(int j=i+1;j<multiPolygonGeometryList.size();j++){
                    geometry2 = multiPolygonGeometryList.get(j);
                    //自相交
                    //Geometry geometry2IntersectGeometry2 = geometry2.intersection(geometry2);
                    //Geometry geometry1IntersectGeometry2 = geometry1IntersectGeometry1.intersection(geometry2IntersectGeometry2);
                    //double area = geometry1IntersectGeometry2.getArea();
                    //两两相交
                    Geometry geometry1IntersectGeometry2 = geometry1.intersection(geometry2);
                    double area = geometry1IntersectGeometry2.getArea();
                    if(area >= GLOBAL_THRESH){
                        resultStr = "isPolygonsIntersect";
                        String temp = "存在两两重叠或相交";
                        //temp += "，面："+geometry1.toString();
                        //temp += "相交于面："+geometry2.toString();
                        temp += "，相交面积："+area;
                        System.out.println(temp);
                        break;
                    }
                }
                if(resultStr!="校验成功"){
                    break;
                }
            }
        }

        return resultStr;
    }

    //校验矢量面数据是否在省市县所在区域边界内
    public boolean newCheckPointIsInDistrict(List<com.css.fxfzypg.modules.spatialData.repository.entity.Point[]> boundaries,List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon> polygonList) {
        com.css.fxfzypg.modules.spatialData.repository.entity.Point point = null;
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Point> pointArray = null;
        com.css.fxfzypg.modules.spatialData.repository.entity.Point[] boundary = null;
        com.css.fxfzypg.modules.spatialData.repository.entity.Polygon polygon = null;

        if(boundaries!=null && boundaries.size()>0 && polygonList!=null && polygonList.size()>0){
            for(int i=0;i<polygonList.size();i++){
                boolean bool = false;
                polygon = polygonList.get(i);
                pointArray = polygon.points;
                if(pointArray!=null && pointArray.size()>0){
                    for(int j=0;j<pointArray.size();j++){
                        point = pointArray.get(j);
                        bool = false;
                        double minDis = Double.MAX_VALUE;
                        for (int k = 0; k < boundaries.size(); k++) {
                            boundary = boundaries.get(k);
                            if (AreaBoundaryUtil.isPointInPolygon(point, boundary)){
                                bool = true;
                                break;
                            } else {//判断容差距离
                                //double minDis = Double.MAX_VALUE;
                                for (int n = 0; n < boundary.length - 1; n++) {
                                    com.css.fxfzypg.modules.spatialData.repository.entity.Point p1 = boundary[n], p2 = boundary[n + 1];
                                    double d = AreaBoundaryUtil.pointToLine(p1.x, p1.y, p2.x, p2.y, point.x, point.y);
                                    if (minDis > d) minDis = d;
                                }
                                if (minDis < GLOBAL_THRESH) {
                                    bool = true;
                                    break;
                                }
                            }
                        }
                        if (bool == false){
                            String temp = "矢量面上的点："+point;
                            temp+="--------不在行政区划范围内----minDis:"+minDis;
                            System.out.println(temp);
                            return false;
                        }
                    }
                }
            }
        }else{
            System.out.println("无行政区划范围----");
            return false;
        }

        return true;
    }

    //校验点数据是否在省市县所在区域边界内
    public boolean newCheckPointIsInDistrictBoundary(List<com.css.fxfzypg.modules.spatialData.repository.entity.Point[]> boundaries,String lonStr, String latStr) {
        com.css.fxfzypg.modules.spatialData.repository.entity.Point point = new com.css.fxfzypg.modules.spatialData.repository.entity.Point(Double.parseDouble(lonStr), Double.parseDouble(latStr));
        com.css.fxfzypg.modules.spatialData.repository.entity.Point[] boundary = null;
        boolean bool = false;
        if(boundaries!=null && boundaries.size()>0){
            for (int k = 0; k < boundaries.size(); k++) {
                boundary = boundaries.get(k);
                if (AreaBoundaryUtil.isPointInPolygon(point, boundary)){
                    bool = true;
                    break;
                } else {//判断容差距离
                    double minDis = Double.MAX_VALUE;
                    for (int n = 0; n < boundary.length - 1; n++) {
                        com.css.fxfzypg.modules.spatialData.repository.entity.Point p1 = boundary[n], p2 = boundary[n + 1];
                        double d = AreaBoundaryUtil.pointToLine(p1.x, p1.y, p2.x, p2.y, point.x, point.y);
                        if (minDis > d) minDis = d;
                    }
                    if (minDis < GLOBAL_THRESH) {
                        bool = true;
                        break;
                    }
                }
            }
            if (bool == false){
                String temp = "点："+point+"--------不在行政区划范围内----";
                System.out.println(temp);
                return false;
            }
        }else{
            System.out.println("无行政区划范围----");
            return false;
        }

        return true;
    }

    private String strWKTMercator = "PROJCS[\"CGCS2000_GK_Zone_20\",GEOGCS[\"GCS_China_Geodetic_Coordinate_System_2000\",DATUM[\"D_China_2000\",SPHEROID[\"CGCS2000\",6378137.0,298.257222101]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Gauss_Kruger\"],PARAMETER[\"False_Easting\",20500000.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",117.0],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0],UNIT[\"Meter\",1.0]]";

    public void setStrWKTMercator(String wKTMercator){
        strWKTMercator = wKTMercator;
    }

    public String wkt2lonLat(String wktPolygon){
        Geometry geomtry = null;
        try {
            GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
            WKTReader reader = new WKTReader(geometryFactory);
            geomtry = reader.read(wktPolygon);
            geomtry = webMercator2lonLat(geomtry);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if (geomtry != null)
            return geomtry.toString();
        else return null;
    }

    public Geometry webMercator2lonLat(Geometry geom){
        try{
            CoordinateReferenceSystem sourceTarget = CRS.parseWKT(strWKTMercator);
            CoordinateReferenceSystem crsTarget = CRS.decode("EPSG:4490");
            MathTransform transform = CRS.findMathTransform(sourceTarget, crsTarget, true);
            //MathTransform transform = CRS.findMathTransform(sourceTarget, DefaultGeographicCRS.WGS84, true);
            return JTS.transform(geom, transform);
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //获取重点活动ID（11位）
    public String getZdhdId(String dateStr, int fileListCount){
        String zdhdId = dateStr;
        fileListCount = fileListCount - 1;//从0开始
        if(fileListCount<10){
            zdhdId += "00" + fileListCount;
        }else if(fileListCount<100){
            zdhdId += "0" + fileListCount;
        }else if(fileListCount<1000){
            zdhdId += String.valueOf(fileListCount);
        }

        return zdhdId;
    }

    //获取流水码（5位)
    public String getTempCountNum(int count){
        count = count - 1;//从0开始
        //流水码（5位）
        String tempCountNum = "00000";
        if(count<10){
            tempCountNum = "0000" + count;
        }else if(count<100){
            tempCountNum = "000" + count;
        }else if(count<1000){
            tempCountNum = "00" + count;
        }else if(count<10000){
            tempCountNum = "0" + count;
        }else if(count<100000){
            tempCountNum = String.valueOf(count);
        }else{//超过5位
            tempCountNum = String.valueOf(count);
        }

        return tempCountNum;
    }

    //判断字符串是否为整数或者小数（大于0）
    public static boolean isNumericFloat(String str){
        Pattern pattern = Pattern.compile("[0-9]*\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        float temp = Float.parseFloat(str);
        if(temp>0){
            return true;
        }else{
            return false;
        }
    }

    //处理空间数据，判断存在自相交则获取修复后的空间数据，否则返回原空间数据wkt
    @Override
    public String getGeomValidWkt(String geomText) {
        String valid = isGeomValid(geomText);
        if(valid.equals("t")){//正常
            //
        }else if(valid.equals("f")){//自相交
            //修复空间数据自相交，获取修复后的空间数据
            geomText = makeGeomValid(geomText);
        }
        //保持空间数据类型一致性
        if(geomText.indexOf("POLYGON")==0){//面转多面
            geomText = "MULTIPOLYGON(" + geomText.split("POLYGON")[1] + ")";
        }
        return geomText;
    }

    //校验空间数据是否自相交
    @Override
    public String isGeomValid(String geomText) {
        String sql = "SELECT ST_IsValid(geom) FROM st_geomfromtext(?,4490) geom";

        return jdbcTemplate.queryForObject(sql, String.class, geomText);
    }

    //修复空间数据自相交，获取修复后的空间数据
    @Override
    public String makeGeomValid(String geomText) {
        String sql = "SELECT ST_AsText(ST_MakeValid(geom)) FROM st_geomfromtext(?,4490) geom";

        return jdbcTemplate.queryForObject(sql, String.class, geomText);
    }

    //获取任务区域合并后的空间数据
    @Override
    public String getTaskRegionGeomUnion(String taskRegion) {
        String sql = "select st_astext(st_union(st_geomfromtext(a.geomtext,4490))) from " +
                "(SELECT regexp_split_to_table (?, ';') as geomtext) a";
        return jdbcTemplate.queryForObject(sql, String.class, taskRegion);
    }

    //读取shp文件并校验--type上传类型（导入任务区域_）
    public List<Object> readSHPFileCheck1(String path, String codeType) {
        List<Object> result = new ArrayList<Object>();
        String prjPath = path.substring(0, path.length() - 4) + ".prj";
        String strWKTMercator = readPRJ(prjPath);
        if (strWKTMercator != "") setStrWKTMercator(strWKTMercator);
        SimpleFeatureCollection colls1 = readShp(path, null, codeType);
        SimpleFeatureIterator iters = colls1.features();
        String resMsg = "校验成功";
        int count = 0;
        SimpleFeature sf = null;
        List<String> wktList = new ArrayList<>();

        while (iters.hasNext()) {
            if(count%100000==0){
                System.out.println(count);
            }
            sf = iters.next();
            List<Object> attributes = sf.getAttributes();
            //0.判断字段数量是否符合要求
            int size = attributes.size();
            if(size==0){
                resMsg = "fieldNumError";
                break;
            }
            if(attributes.get(0)==null){
                resMsg = "fieldNullValue";
                break;
            }
            String polygonWkt = attributes.get(0).toString();
            if(!polygonWkt.contains("POLYGON")){
                resMsg = "geomTypeError";
                break;
            }
            wktList.add(polygonWkt);
            if(!resMsg.equals("校验成功")){
                break;
            }

            count++;
        }
        iters.close();
        System.out.println(count);
        if(count>1){
            resMsg = "多条空间数据";
            wktList = null;
        }

        //返回结果
        result.add(codeType);//编码类型（0：UTF-8，1：GBK）
        result.add(count);//数据长度
        result.add(resMsg);//校验结果
        result.add(wktList);//空间数据列表

        return result;
    }

    //shp导入任务区域校验并获取空间数据
    public String checkSHPFiles1(String filePath) {
        try {
            String returnMsg = "";
            System.out.println(new Date()+"-------------------1.开始readSHPFile");
            System.out.println(new Date()+"-------------------2.开始校验");
            //校验是否为2000坐标系
            if (!(checkCGCS2000(filePath))){
                System.out.println(new Date()+"-----------校验失败.请上传正确的CGCS2000坐标系数据及.prj文件.");
                return "checkNotCGCS2000";
            }
//            String cpgPath = filePath.substring(0, filePath.length() - 4) + ".cpg";
//            String codeType = readCPG(cpgPath);//读取cpg文件编码
            String codeType = "UTF-8";//默认文件编码
            //读取shp文件并校验--type上传类型（行政区划_）
            List<Object> list = readSHPFileCheck1(filePath, codeType);
            codeType = (String) list.get(0);//编码类型（0：UTF-8，1：GBK）
            int dataLength = (int) list.get(1);//数据长度
            String checkResult = (String) list.get(2);//校验结果
            List<String> wktList = (List<String>) list.get(3);//空间数据列表
            //编码类型（0：UTF-8，1：GBK）
//            if (codeType.equals("UTF-8")) {
//                codeType = "0";
//            }else{
//                codeType = "1";
//            }
            System.out.println(new Date()+"-------------------3.结束readSHPFile");
            System.out.println(new Date()+"-----------4.结束校验");
            if(checkResult.equals("校验成功")){
                System.out.println(new Date()+"-----------校验成功.");
                String fileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length() - 4);
                System.out.println(new Date()+"-------------------4.开始获取面数据");
                String wktString = "MULTIPOLYGON (";
                for(int i=0;i<wktList.size();i++){
                    if(i>0){
                        wktString += ",";
                    }
                    String wkt = wktList.get(i);
                    if (wkt.indexOf("MULTIPOLYGON") != -1) {
                        wkt = wkt.replace("MULTIPOLYGON (","");
                        wkt = wkt.substring(0, wkt.lastIndexOf(")"));
                        wktString += wkt;
                    }else if (wkt.indexOf("POLYGON") != -1){
                        wkt = wkt.replace("POLYGON","");
                        wktString += wkt;
                    }
                }
                wktString += ")";

                //校验是否自相交
                String valid = isGeomValid(wktString);
                if(valid.equals("t")){//正常
                    returnMsg = "导入成功."+wktString;
                }else if(valid.equals("f")) {//自相交
                    returnMsg = "空间数据自相交";
                }
//                returnMsg = "导入成功."+wktString;
                System.out.println(new Date()+"-------------------5.结束获取面数据");
            } else{
                System.out.println(new Date()+"-----------校验失败."+checkResult);
                returnMsg = "上传文件中第"+(dataLength+1)+"行数据#" + checkResult;
            }
            //返回的消息
            return returnMsg;
        } catch (RuntimeException e) {
            log.error(e.getMessage(), e);
            return "导入出现错误: <br/>" + e.getMessage();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "数据导入失败, 服务器内部出现异常!";
        }
    }

    //读取txt文件并校验--type上传类型（导入任务区域_）
    public List<Object> readTxtFileCheck(String path) {
        List<Object> result = new ArrayList<Object>();
        String resMsg = "校验成功";
        List<String> wktList = new ArrayList<>();
        List<String> lonlatList = new ArrayList<>();
        File file = new File(path);
        int count = 0;
        try {
            FileReader fileReader = new FileReader(file);
            BufferedReader reader = new BufferedReader(fileReader);
            String line;
            while ((line = reader.readLine()) != null) {
                // 处理每一行的数据
//                System.out.println(line);
                if (!PlatformObjectUtils.isEmpty(line)) {
                    String[] lonlat = line.split("\t");//制表符间隔经纬度
                    if(lonlat!=null && lonlat.length==2){
                        double lon = Double.valueOf(lonlat[0]);
                        double lat = Double.valueOf(lonlat[1]);
                        if(lon>=-180 && lon<=180 && lat>=-90 && lat<=90){
                            lonlatList.add(lon+" "+lat);
                        }else{
                            resMsg = "geomTypeError";
                            break;
                        }
                    }
                    count++;
                }
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(resMsg.equals("校验成功")){
            if(lonlatList.size()>=3){
                String wkt = "MULTIPOLYGON (((";
                for(int i=0;i<lonlatList.size();i++){
                    if(i>0){
                        wkt += ",";
                    }
                    wkt += lonlatList.get(i);
                }
                String startLonLat = lonlatList.get(0);
                String lastLonLat = lonlatList.get(lonlatList.size()-1);
                if(!startLonLat.equals(lastLonLat)){//面数据最后1个点应与第1个点相同
                    wkt += "," + startLonLat;
                }
                wkt += ")))";
                wktList.add(wkt);
            }else{
                resMsg = "geomTypeError";
            }
        }

        //返回结果
        result.add(resMsg);//校验结果
        result.add(wktList);//空间数据列表
        result.add(count);//数据长度

        return result;
    }

    //txt导入任务区域校验并获取空间数据
    public String checkTxtFiles(String filePath) {
        try {
            String returnMsg = "";
            System.out.println(new Date()+"-------------------1.开始readTxtFile");
            System.out.println(new Date()+"-------------------2.开始校验");

            //读取shp文件并校验--type上传类型（导入任务区域_）
            List<Object> list = readTxtFileCheck(filePath);
            String checkResult = (String) list.get(0);//校验结果
            List<String> wktList = (List<String>) list.get(1);//空间数据列表
            int dataLength = (int) list.get(2);//数据长度

            System.out.println(new Date()+"-------------------3.结束readTxtFile");
            System.out.println(new Date()+"-----------4.结束校验");
            if(checkResult.equals("校验成功")){
                System.out.println(new Date()+"-----------校验成功.");
                String fileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length() - 4);
                System.out.println(new Date()+"-------------------4.开始获取面数据");
                String wktString = "MULTIPOLYGON (";
                for(int i=0;i<wktList.size();i++){
                    if(i>0){
                        wktString += ",";
                    }
                    String wkt = wktList.get(i);
                    if (wkt.indexOf("MULTIPOLYGON") != -1) {
                        wkt = wkt.replace("MULTIPOLYGON (","");
                        wkt = wkt.substring(0, wkt.lastIndexOf(")"));
                        wktString += wkt;
                    }else if (wkt.indexOf("POLYGON") != -1){
                        wkt = wkt.replace("POLYGON","");
                        wktString += wkt;
                    }
                }
                wktString += ")";

                returnMsg = "导入成功."+wktString;
                System.out.println(new Date()+"-------------------5.结束获取面数据");
            }else{
                System.out.println(new Date()+"-----------校验失败."+checkResult);
                returnMsg = "上传文件中第"+(dataLength+1)+"行数据#" + checkResult;
            }
            //返回的消息
            return returnMsg;
        } catch (RuntimeException e) {
            log.error(e.getMessage(), e);
            return "导入出现错误: <br/>" + e.getMessage();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "数据导入失败, 服务器内部出现异常!";
        }
    }

    //根据行政区划code按6度带投影计算空间数据面积
    @Override
    public String getAreaByCodeEPSG6(String code) {
        String area = null;
        try{
            //CGCS2000 6度分
            //4502--CGCS2000_GK_CM_75E--中央子午线75E，带号13  72--78
            //4512--CGCS2000_GK_CM_135E--中央子午线135E，带号23  132-138
            String sql = "select st_area(st_transform(st_geomfromtext(coordinate,4490),(floor((st_x(st_centroid(st_geomfromtext(coordinate,4490)))-72)/6)-10+4512)::int4)) from district_boundary where code=? limit 1";

            area = jdbcTemplate.queryForObject(sql, String.class, code);
        }catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return area;
    }

    //根据行政区划code按3度带投影计算空间数据面积
    @Override
    public String getAreaByCodeEPSG3(String code) {
        String area = null;
        try{
            //test
            code = "441900";
            //CGCS2000 3度分
            //4534--CGCS2000_3_Degree_GK_CM_75E--中央子午线75E，带号25  73.5--76.5
            //4554--CGCS2000_3_Degree_GK_CM_135E--中央子午线135E，带号45  133.5--136.5
            String sql = "select st_area(st_transform(st_geomfromtext(coordinate,4490),(floor((st_x(st_centroid(st_geomfromtext(coordinate,4490)))-73.5)/3)-20+4554)::int4)) from district_boundary where code=? limit 1";

            area = jdbcTemplate.queryForObject(sql, String.class, code);
        }catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return area;
    }

    //按6度带投影计算空间数据面积
    @Override
    public String getAreaByGeomEPSG6(String geomText) {
        //CGCS2000 6度分
        //4502--CGCS2000_GK_CM_75E--中央子午线75E，带号13  72--78
        //4512--CGCS2000_GK_CM_135E--中央子午线135E，带号23  132-138
        String sql = "select st_area(st_transform(st_geomfromtext(?,4490),(floor((st_x(st_centroid(st_geomfromtext(?,4490)))-72)/6)-10+4512)::int4))";

        return jdbcTemplate.queryForObject(sql, String.class, geomText, geomText);
    }

    //按3度带投影计算空间数据面积
    @Override
    public String getAreaByGeomEPSG3(String geomText) {
        //CGCS2000 3度分
        //4534--CGCS2000_3_Degree_GK_CM_75E--中央子午线75E，带号25  73.5--76.5
        //4554--CGCS2000_3_Degree_GK_CM_135E--中央子午线135E，带号45  133.5--136.5
        String sql = "select st_area(st_transform(st_geomfromtext(?,4490),(floor((st_x(st_centroid(st_geomfromtext(?,4490)))-73.5)/3)-20+4554)::int4))";

        return jdbcTemplate.queryForObject(sql, String.class, geomText, geomText);
    }

    //根据空间数据wkt获取投影坐标EPSG
    @Override
    public int getEPSGFromGeomText(String geomText) {
        int epsg = 0;
        if (PlatformObjectUtils.isNotEmpty(geomText)) {
            //获取区域范围extent经纬度
            List<Double> lonlatList = getGeomExtentLonLat(geomText);
            if (lonlatList.size() == 4) {
                double minLon = lonlatList.get(0);//最小经度
                double minLat = lonlatList.get(1);//最小纬度
                double maxLon = lonlatList.get(2);//最大经度
                double maxLat = lonlatList.get(3);//最大纬度
                double temp = (maxLon - minLon) / 3;
                int minEpsg = 0;
                int maxEpsg = 0;
                int type = 6;//投影带类型3度带|6度带
                if (temp > 1) {//根据经度获取投影坐标--6度带
                    type = 6;
                    minEpsg = getEPSGFromLon6(minLon);
                    maxEpsg = getEPSGFromLon6(maxLon);
                } else {//根据经度获取投影坐标--3度带
                    type = 3;
                    minEpsg = getEPSGFromLon3(minLon);
                    maxEpsg = getEPSGFromLon3(maxLon);
                }
                if (minEpsg > 0 && maxEpsg > 0) {
                    if (minEpsg == maxEpsg) {//同一投影带
                        epsg = minEpsg;
                    } else {//不同投影带
                        //获取中心点所在的投影带
                        List<String> centerLonLat = getCenterLonLat(geomText);
                        if (centerLonLat.size() == 2) {
                            //中心点经度
                            double centerLon = Double.valueOf(centerLonLat.get(0));
                            //根据经度获取投影坐标--6度带
                            epsg = getEPSGFromLon6(centerLon);
                        }
                    }
                }
            }
        }

        return epsg;
    }

    //获取区域范围extent经纬度
    @Override
    public List<Double> getGeomExtentLonLat(String geomText) {
        List<Double> lonlatList = new ArrayList<Double>();
        String sql = "select st_extent(st_geomfromtext(?,4490))";
        String boxExtent = jdbcTemplate.queryForObject(sql, String.class, geomText);
        if (PlatformObjectUtils.isNotEmpty(boxExtent) && boxExtent.indexOf("BOX(") == 0) {
            String box = boxExtent.replace("BOX(", "").replace(")", "");
            String[] lonlatArr = box.split(",");
            String[] minLonLat = lonlatArr[0].split(" ");
            String[] maxLonLat = lonlatArr[1].split(" ");
            if (minLonLat.length == 2 && maxLonLat.length == 2) {
                lonlatList.add(Double.valueOf(minLonLat[0]));//最小经度
                lonlatList.add(Double.valueOf(minLonLat[1]));//最小纬度
                lonlatList.add(Double.valueOf(maxLonLat[0]));//最大经度
                lonlatList.add(Double.valueOf(maxLonLat[1]));//最大纬度
            }
        }

        return lonlatList;
    }

    //获取中心点经纬度
    @Override
    public List<String> getCenterLonLat(String geomText) {
        List<String> centerLonLat = new ArrayList<>();
        if (PlatformObjectUtils.isNotEmpty(geomText)) {
            String sql = "SELECT st_astext(st_centroid(st_geometryfromtext(?,4490)))";
            String centerPoint = jdbcTemplate.queryForObject(sql, String.class, geomText);
            if (PlatformObjectUtils.isNotEmpty(centerPoint) && centerPoint.indexOf("POINT(") != -1) {
                String lonlatStr = centerPoint.replace("POINT(", "").replace(")", "");
                String[] lonlat = lonlatStr.split(" ");
                if (lonlat.length == 2) {
                    centerLonLat.add(lonlat[0]);//经度
                    centerLonLat.add(lonlat[1]);//纬度
                }
            }
        }

        return centerLonLat;
    }

    //3°带中，中央子午线=带号×3
    //根据经度获取投影坐标--3度带
    @Override
    public int getEPSGFromLon3(double srcLon) {
        int epsg = 0;
        int index = 0;
        //4534--CGCS2000_3_Degree_GK_CM_75E--中央子午线75E，带号25
        double startLon = 75 - 1.5;
        //4554--CGCS2000_3_Degree_GK_CM_135E--中央子午线135E，带号45
        double endLon = 135 + 1.5;
        boolean bool = true;
        while (bool) {
            if (srcLon >= startLon && srcLon < (startLon + 3)) {
                epsg = 4534 + index;
                bool = false;
            } else if (srcLon < startLon || srcLon > endLon) {
                epsg = 0;
                bool = false;
            } else {
                index++;
                startLon += 3;
            }
        }

        return epsg;
    }

    //6°带中，中央子午线=带号×6-3
    //根据经度获取投影坐标--6度带
    @Override
    public int getEPSGFromLon6(double srcLon) {
        int epsg = 0;
        int index = 0;
        //4502--CGCS2000_GK_CM_75E--中央子午线75E，带号13
        double startLon = 75 - 3;
        //4512--CGCS2000_GK_CM_135E--中央子午线135E，带号23
        double endLon = 135 + 3;
        boolean bool = true;
        while (bool) {
            if (srcLon >= startLon && srcLon < (startLon + 6)) {
                epsg = 4502 + index;
                bool = false;
            } else if (srcLon < startLon || srcLon > endLon) {
                epsg = 0;
                bool = false;
            } else {
                index++;
                startLon += 6;
            }
        }

        return epsg;
    }

    //根据区域投影到6度带或3度带，计算投影面积之和（平方公里)
    @Override
    public BigDecimal getAreaByGeomEpsgCount(String geomText) {
        BigDecimal area = BigDecimal.ZERO;
        //获取区域范围extent经纬度
        List<Double> lonlatList = getGeomExtentLonLat(geomText);
        if (lonlatList.size() == 4) {
            double minLon = lonlatList.get(0);//最小经度
            double minLat = lonlatList.get(1);//最小纬度
            double maxLon = lonlatList.get(2);//最大经度
            double maxLat = lonlatList.get(3);//最大纬度
            double temp = (maxLon - minLon) / 3;
            int minEpsg = 0;
            int maxEpsg = 0;
            int epsg = 0;
            int type = 6;//投影带类型3度带|6度带
            if (temp > 1) {//根据经度获取投影坐标--6度带
                type = 6;
                minEpsg = getEPSGFromLon6(minLon);
                maxEpsg = getEPSGFromLon6(maxLon);
            } else {//根据经度获取投影坐标--3度带
                type = 3;
                minEpsg = getEPSGFromLon3(minLon);
                maxEpsg = getEPSGFromLon3(maxLon);
            }
            if (minEpsg > 0 && maxEpsg > 0) {
                if (minEpsg == maxEpsg) {//同一投影带
                    epsg = minEpsg;
                    //根据投影坐标计算空间数据投影面积
                    area = getAreaByGeomEpsg(geomText, epsg);
                } else {//不同投影带
                    //用投影带分割面
                    List<String> allPolygonList = splitEpsgGeomList(geomText, minEpsg, maxEpsg, type);
                    if (allPolygonList.size() > 0) {
                        for (int i = 0; i < allPolygonList.size(); i++) {
                            epsg = minEpsg + i;
                            String geomTemp = allPolygonList.get(i);
                            //根据投影坐标计算空间数据投影面积
                            BigDecimal areaTemp = getAreaByGeomEpsg(geomTemp, epsg);
                            area = area.add(areaTemp);
                        }
                    }
                }
            }
        }
        if (area.compareTo(BigDecimal.ZERO) > 0) {
            area = area.divide(BigDecimal.valueOf(1000000));//平方公里
        }

        return area;
    }

    //根据投影坐标计算空间数据投影面积
    public BigDecimal getAreaByGeomEpsg(String geomText, int epsg) {
        String sql = "SELECT st_area(ST_Transform(st_geometryfromtext(?,4490)," + epsg + "))";

        return jdbcTemplate.queryForObject(sql, BigDecimal.class, geomText);
    }

    //用投影带分割面
    public List<String> splitEpsgGeomList(String geomText, int minEpsg, int maxEpsg, int type) {
        String lineText = "MULTILINESTRING(";
        if (type == 6) {//6度带
            //4502--CGCS2000_GK_CM_75E--中央子午线75E，带号13
            double startLon = 75 - 3;
            //4512--CGCS2000_GK_CM_135E--中央子午线135E，带号23
            double endLon = 135 + 3;
            int temp = maxEpsg - minEpsg;
            for (int i = 0; i < temp; i++) {
                double lon = (minEpsg - 4502 + i + 1) * 6 + startLon;
                if (i > 0) {
                    lineText += ",";
                }
                lineText += "(" + lon + " 90," + lon + " 0)";
            }
        } else if (type == 3) {//3度带
            //4534--CGCS2000_3_Degree_GK_CM_75E--中央子午线75E，带号25
            double startLon = 75 - 1.5;
            //4554--CGCS2000_3_Degree_GK_CM_135E--中央子午线135E，带号45
            double endLon = 135 + 1.5;
            int temp = maxEpsg - minEpsg;
            for (int i = 0; i < temp; i++) {
                double lon = (minEpsg - 4534 + i + 1) * 3 + startLon;
                if (i > 0) {
                    lineText += ",";
                }
                lineText += "(" + lon + " 90," + lon + " 0)";
            }
        }
        lineText += ")";
        //用线分割面
        List<String> allPolygonList = splitPolygonByLine(geomText, lineText);

        return allPolygonList;
    }

    //用线分割面
    public List<String> splitPolygonByLine(String polygonText, String lineText) {
        List<String> polygonList = new ArrayList<>();
        String sql = "SELECT st_astext(st_split(st_geomfromtext(?,4490),st_geomfromtext(?,4490)))";
        String collection = jdbcTemplate.queryForObject(sql, String.class, polygonText, lineText);
        if (PlatformObjectUtils.isNotEmpty(collection) && collection.indexOf("GEOMETRYCOLLECTION(") == 0) {
            collection = collection.replace("GEOMETRYCOLLECTION(", "");
            collection = collection.substring(0, collection.length() - 1);
            if (collection.contains("POLYGON((")) {
                if (collection.contains(")),POLYGON((")) {//多个
                    String[] temp = collection.split("\\)\\),POLYGON\\(\\(");
                    for (int i = 0; i < temp.length; i++) {
                        if (i == 0) {
                            String polygon = temp[i] + "))";
                            polygonList.add(polygon);
                        } else if (i == (temp.length - 1)) {
                            String polygon = "POLYGON((" + temp[i];
                            polygonList.add(polygon);
                        } else {
                            String polygon = "POLYGON((" + temp[i] + "))";
                            polygonList.add(polygon);
                        }
                    }
                } else {//1个
                    String polygon = collection;
                    polygonList.add(polygon);
                }
            }
        }

        return polygonList;
    }
}
